<template>
  <div class="category">
    <el-row class="category-row" type="flex">
      <span class="item" :class="[current == -1 ? 'active' : '']" @click="onRecommend">推荐</span>
      <span
        class="item"
        v-for="(item, index) in list"
        :key="index"
        @click="handleChange(item)"
        :class="[item.id == current ? 'active' : '']"
        >{{ item.title }}</span
      >
    </el-row>
    <el-row class="category-row" type="flex">
      <span
        class="item gray"
        v-for="(item, index) in categoryList"
        :key="index"
        @click="onPatch(item.id)"
        :class="[item.id == category ? 'active' : '']"
        >{{ item.title }}</span
      >
    </el-row>
  </div>
</template>
<script>
export default {
  name: 'category',
  components: {},
  data() {
    return {
      list: [],
      categoryList: [],
      current: -1,
      category: 0
    }
  },
  methods: {
    // 获取分类数据
    getCategoryInfo() {
      this.$api.getCategory(
        {
          type: 6
        },
        res => {
          const { data } = res
          this.list = data
        }
      )
    },
    // 推荐
    onRecommend() {
      this.current = -1
      this.category = 0
      this.categoryList = []
      this.$emit('patch', -1)
    },
    // 一级
    handleChange(item) {
      if (item.id == this.current) return
      this.current = item.id
      this.categoryList = item.child || []
      let data = this.categoryList.some(v => v.id == item.id)
      if (!this.$util.isEmpty(this.categoryList) && !data) {
        let query = {
          id: item.id,
          pid: item.id,
          title: '全部'
        }
        this.categoryList.unshift(query)
      }
      this.category = item.id
      this.$emit('patch', this.category)
    },
    // 二级
    onPatch(id) {
      if (id == this.category) return
      this.category = id
      this.$emit('patch', id)
    }
  },
  created() {
    this.getCategoryInfo()
  }
}
</script>
<style lang="scss" scoped>
.category {
  .category-row {
    flex-wrap: wrap;
    .item {
      margin-bottom: 20px;
      margin-right: 10px;
      font-size: 14px;
      font-weight: 400;
      line-height: 1;
      color: $text-color-import;
      padding: 6px 11px;
      cursor: pointer;
      &.active {
        color: #ffffff;
        border-radius: 13px;
        background: linear-gradient(90deg, #ff3b2f 0%, #ff8a52 100%);
      }
    }
    .gray {
      color: #7d7d7d;
    }
  }
}
</style>
